﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using OpenFlashChart;
using ToolTip = OpenFlashChart.ToolTip;
using ToolTipStyle = OpenFlashChart.ToolTipStyle;
using System.Collections;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class companyDataAnalysis : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("EE", 1))
                {
                    ddlCompanyBind();
                    RenderChart();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        private void ddlCompanyBind()
        {
            DataTable dt = logic.company.listWithCompanyType("2");
            ddlCompany.DataSource = dt;
            ddlCompany.DataBind();
        }
        
        protected void btnAnalysis_Click(object sender, EventArgs e)
        {
            RenderChart();
        }

        private void RenderChart()
        {
            int companyId = 0;
            int.TryParse(ddlCompany.SelectedValue, out companyId);
            int year = DateTime.Now.Year;
            int.TryParse(ddlYear.SelectedValue, out year);

            DataTable dt = new DataTable();

            if (radModeW.Checked)
            {
                dv1.Visible = true;
                dv2.Visible = false;
                if (!chkEnableCompany.Checked)
                {
                    companyId = -1;
                }
                dt = logic.company.listCompanyDataAnalysisByCriteria(companyId, year,"W");

                rpt_list.DataSource = dt;
                rpt_list.DataBind();

                RenderChart(dt);
            }
            else if (radModeD.Checked)
            {
                dv1.Visible = false;
                dv2.Visible = true;
                if (!chkEnableCompany.Checked)
                {
                    companyId = -1;
                }
                dt = logic.company.listCompanyDataAnalysisByCriteria(companyId, year, "D");
                StringBuilder chart_settings = new StringBuilder(GenerateHtml());
                StringBuilder data_file = new StringBuilder();

                foreach (DataRow row in dt.Rows)
                {
                    data_file.AppendFormat("{0},{1:F2}\\n", row["orderDt"], row["totalAmount"]);
                }

                chart_settings.Replace("#data#", data_file.ToString());

                StringBuilder script = new StringBuilder("<script type='text/javascript'>");
                script.Append(@"var so = new SWFObject(""../amstock/amstock.swf"", ""amstock"", ""1120"", ""350"", ""8"", ""#FFFFFF"");");
                script.AppendFormat(@"so.addParam(""wmode"",""transparent"");");
                script.AppendFormat(@"so.addVariable(""chart_settings"", encodeURIComponent(""{0}""));", chart_settings.ToString());
                script.Append(@"so.addVariable(""data_file"", encodeURIComponent(""amstock/amstock_data.null""));");
                script.Append(@"so.write(""flashcontent"");");
                script.Append("</script>");

                scrptLayout.Text = script.ToString();
            }
        }

        private void RenderChart(DataTable dt)
        {

            object maxYValue = dt.Compute("MAX(totalAmount)", "");
            object minYValue = dt.Compute("MIN(totalAmount)", "");

            OpenFlashChart.OpenFlashChart chart = new OpenFlashChart.OpenFlashChart();

            ArrayList data1 = new ArrayList();
            IList<string> weekLabels = new List<string>();

            foreach (DataRow row in dt.Rows)
            {
                data1.Add(new LineDotValue(Convert.ToDouble(row["totalAmount"]), string.Format("第{0}周订购量{1:F2}", row["weekNum"], row["totalAmount"]), "#fe0"));
                weekLabels.Add(row["weekNum"].ToString());
            }
            //Random rand = new Random(DateTime.Now.Millisecond);
            //for (double i = 0; i < 365; i++)
            //{
            //    data1.Add(rand.Next(30));
            //    weekLabels.Add((i + 1).ToString());
            //}

            OpenFlashChart.LineHollow line1 = new LineHollow();
            line1.Values = data1;
            line1.HaloSize = 0;
            line1.Width = 2;
            line1.DotSize = 5;
            line1.Text = "周订购量";

            line1.Tooltip = "提示：#val#";

            chart.X_Axis.Labels.SetLabels(weekLabels);

            chart.AddElement(line1);

            if (chkEnableCompany.Checked)
            {
                chart.Title = new Title(string.Format("{0}{1}年周订购量", ddlCompany.SelectedItem.Text, ddlYear.SelectedItem.Text));
                chart.Y_Axis.SetRange(0,Convert.ToInt32(maxYValue), 5000);
            }
            else
            {
                chart.Title = new Title(string.Format("{0}年平台周订购量", ddlYear.SelectedItem.Text));
                chart.Y_Axis.SetRange(0,Convert.ToInt32(maxYValue),50000);
            }

            //chart.Y_Axis.SetRange(0,35,5);
            chart.Tooltip = new ToolTip("全局提示：#val#");
            chart.Tooltip.Shadow = true;
            chart.Tooltip.Colour = "#e43456";
            chart.Tooltip.MouseStyle = ToolTipStyle.CLOSEST;
            OpenFlashChartControl1.EnableCache = false;
            OpenFlashChartControl1.Chart = chart;
        }

        private string GenerateHtml()
        {
            StringBuilder append = new StringBuilder();
            append.Append("<settings>");

            append.Append("<strings>");
            append.Append("<processing_data>正在处理数据</processing_data>");
            append.Append("<loading_data>正在加载数据</loading_data>");
            append.Append("<wrong_date_format>输入的日期格式不正确</wrong_date_format>");
            append.Append("<no_data>当前没有数据</no_data>");

            append.Append("<months>");
            append.Append("<jan>1</jan>");
            append.Append("<feb>2</feb>");
            append.Append("<mar>3</mar>");
            append.Append("<apr>4</apr>");
            append.Append("<may>5</may>");
            append.Append("<jun>6</jun>");
            append.Append("<jul>7</jul>");
            append.Append("<aug>8</aug>");
            append.Append("<sep>9</sep>");
            append.Append("<oct>10</oct>");
            append.Append("<nov>11</nov>");
            append.Append("<dec>12</dec>");
            append.Append("</months>");

            append.Append("<weekdays>");
            append.Append("<sun>日</sun>");
            append.Append("<mon>一</mon>");
            append.Append("<tue>二</tue>");
            append.Append("<wed>三</wed>");
            append.Append("<thu>四</thu>");
            append.Append("<fri>五</fri>");
            append.Append("<sat>六</sat>");
            append.Append("</weekdays>");

            append.Append("</strings>");

            append.Append("<margins>0</margins>");
            append.Append("<font>Tahoma</font>");
            append.Append("<redraw>true</redraw>");
            append.Append("<number_format>");
            append.Append("<decimal_separator>.</decimal_separator>");
            append.Append("<thousand_separator>,</thousand_separator>");
            append.Append("</number_format>");

            append.Append("<data_sets>");

            append.Append("<data_set did='0'>");
            //append.Append("<color>d764a8</color>");
            append.Append("<color>006600</color>");
            append.Append("<csv>");
            append.Append("<reverse>false</reverse>");
            append.Append("<separator>,</separator>");
            append.Append("<date_format>YYYY-MM-DD</date_format>");
            append.Append("<decimal_separator>.</decimal_separator>");
            append.Append("<columns>");
            append.Append("<column>date</column>");
            append.Append("<column>close</column>");
            append.Append("</columns>");
            append.Append("<data>#data#</data>");
            append.Append("</csv>");
            append.Append("</data_set>");

            append.Append("</data_sets>");

            append.Append("<charts>");

            append.Append("<chart cid='first'>");
            append.Append("<height>60</height>");
            append.Append("<title>订购量：</title>");
            append.Append("<border_color>#CCCCCC</border_color>");
            append.Append("<bg_color>F8F8D8</bg_color>");// 整个区域背景颜色
            append.Append("<border_alpha>100</border_alpha>");

            append.Append("<grid>");
            append.Append("<x>");
            append.Append("<color>F5E1AA</color>");
            append.Append("<alpha>100</alpha>");
            //append.Append("<approx_count>10</approx_count>");
            append.Append("</x>");
            append.Append("<y_left>");
            append.Append("<color>F5E1AA</color>");
            append.Append("<alpha>100</alpha>");
            //append.Append("<approx_count>10</approx_count>");
            append.Append("</y_left>");
            append.Append("<y_right>");
            append.Append("<enabled>0</enabled>");
            append.Append("</y_right>");
            append.Append("</grid>");

            append.Append("<values>");
            append.Append("<x>");
            append.Append("<bg_color>F8F8D8</bg_color>");
            append.Append("</x>");
            append.Append("</values>");

            append.Append("<legend>");
            append.Append("<text_color>FF0000</text_color>");
            append.Append("<show_date>true</show_date>");
            append.Append("</legend>");

            append.Append("<column_width>100</column_width>");

            append.Append("<graphs>");

            append.Append("<graph gid='close'>");
            append.Append("<data_sources>");
            append.Append("<close>close</close>");
            append.Append("</data_sources>");
            append.Append("<bullet>round_outline</bullet>");

            append.Append("<legend>");
            append.Append("<date key='false' title='false'><![CDATA[￥{close}]]></date>");
            append.Append("<period key='false' title='false'><![CDATA[最低订购量:<b>{low}</b> 最高订购量:<b>{high}</b>]]></period>");
            append.Append("</legend>");
            append.Append("<width>2</width>");
            append.Append("</graph>");

            append.Append("</graphs>");
            append.Append("</chart>");
            append.Append("</charts>");

            append.Append("<date_formats>");
            append.Append("<x_axis><days>DD日</days><months>month月</months><years>YYYY年</years></x_axis>");
            append.Append("<legend>");
            append.Append("<days>YYYY年month月DD日</days>");
            append.Append("<weeks>YYYY年month月DD日</weeks>");
            append.Append("</legend>");
            append.Append("</date_formats>");

            append.Append("<data_set_selector>");
            append.Append("<enabled>false</enabled>");
            append.Append("</data_set_selector>");

            append.Append("<period_selector>");

            append.Append("<periods>");
            append.Append("<period type='DD' count='1'>1天</period>");
            append.Append("<period type='DD' count='7'>1周</period>");
            append.Append("<period type='DD' count='10'>10天</period>");
            append.Append("<period type='DD' count='15'>15天</period>");
            append.Append("<period type='MM' count='1'>1个月</period>");
            append.Append("<period type='MM' count='2'>2个月</period>");
            append.Append("<period type='MM' count='3'>3个月</period>");
            append.Append("<period selected='true' type='YYYY' count='1'>1年</period>");
            append.Append("<period type='MAX'>最大</period>");
            append.Append("</periods>");

            append.Append("<periods_title>区间:</periods_title>");
            append.Append("<custom_period_title>选择日期范围:</custom_period_title>");

            append.Append("</period_selector>");

            append.Append("<header>");
            append.Append("<enabled>false</enabled>");
            append.Append("</header>");

            append.Append("<scroller>");
            append.Append("<graph_data_source>close</graph_data_source>");
            append.Append("<resize_button_style>dragger</resize_button_style>");

            append.Append("<playback>");
            append.Append("<enabled>false</enabled>");
            append.Append("</playback>");
            append.Append("</scroller>");

            append.Append("</settings>");

            return append.ToString();
        }
    }
}
